package com.itao.bytebuddy;

import com.itao.util.StringUtil;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.FixedValue;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

import static net.bytebuddy.matcher.ElementMatchers.named;

/**
 * @author sjt
 * @Date 2025/1/21 15:26
 */
public class LoadClass2 {

    public static void main(String[] args) {
        try (
                var unloaded = new ByteBuddy()
                        .redefine(StringUtil.class)
                        //.name("com.itao.bytebuddy.SubClass")
                        .method(named("getString"))
                        .intercept(FixedValue.value("hello"))
                        .make()
        ) {
            var loaded = unloaded
                    // 加载到jvm
                    .load(LoadClass.class.getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
                    // 获得加载的类
                    .getLoaded();

            Constructor<?> constructor = loaded.getDeclaredConstructor();
            Object object = constructor.newInstance();
            Method method = loaded.getDeclaredMethod("getString");
            System.out.println("method.invoke(object) = " + method.invoke(object));
            System.out.println("object.getClass().getClassLoader() = " + object.getClass().getClassLoader());
            StringUtil stringUtil = new StringUtil();
            System.out.println("stringUtil.getString() = " + stringUtil.getString());
            System.out.println("stringUtil.getClass().getClassLoader() = " + stringUtil.getClass().getClassLoader());
            // unloaded.saveIn(new File(ResourceUtil.getClassPath(CreateClass.class)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
